from PIL import Image
from glob import glob
import os.path
from imageio import imread
import numpy as np
import re
import csv
import random
import time
import matplotlib.pyplot as plt
#from skimage import transform,io
# 修改图像分辨率
def resize_image(filein, fileout, scale=1.0):
    img = Image.open(filein)
    width = int(img.size[0] / scale)
    height = int(img.size[1] / scale)
    type = img.format
    out = img.resize((width, height), Image.ANTIALIAS)
    out.save(fileout, type)


# 检查分辨率
def check_ratio(filein):
    img = Image.open(filein)
    if img.size[0] !=1200 or img.size[1]!=900:
        return None
    return img

# 将所有图片分辨率修改40*30并保存到save_Hnd目录下
def resize_all_image():
    # save_path='d:/resize_images/Hnd/Img'
    # os.makedirs(save_path,exist_ok=True)
    names=glob('./Hnd/Img/*/*')
    save_path='./save_Hnd'
    os.makedirs(save_path,exist_ok=True)
    for name in names:
        #resize_image(name,)
        tmp_path=save_path+name[name.rindex('/'):]
        tmp2_path=tmp_path[0:tmp_path.rindex('\\')]
        os.makedirs(tmp2_path,exist_ok=True)
        print(tmp2_path)
        resize_image(name,tmp_path,scale=30)
def char_dir_names(char_dirname):
    return glob('./save_Hnd/Img/'+char_dirname+'/*')
# 将每个图片转换为数组
def img_to_array2(filein):
    # scipy.misc.imread已被禁用
    # img_array=imread(filein)
    # img_flat=img_array.flatten()
    # for _ in img_flat:
    #     print(_)
    # print(len(img_flat))
    # 使用scikitimage进行转换
    # grey=io.imread(filein,as_gray=True)
    # small_grey=transform.resize(grey,(40,30),mode='symmetric',preserve_range=True)
    # reshape_img=small_grey.reshape(1200)
    # for _ in reshape_img:
    #     print(_)
    # print(len(reshape_img))
    # 图像转换为数组
    img_array=imread(filein,as_gray=True)
    # print('img_array:-------------------------------------------------')
    # print(img_array)
    # print(type(img_array))
    # for _ in img_array:
    #     print(_)
    #     print('--------------')
    # # print(len(img_array))
    # plt.imshow(img_array,cmap='Greys',interpolation='None')
    # plt.show()
    img_data=255.0-img_array.reshape(1200)
    # print('img_data:---------------------------')
    # print(img_data)
    # 0~255范围内的输入值除以255得到0~1范围内的输入值，然后乘以0.99，将他们的范围变为0.0~0.99，再加上0.01将范围变为0.01~1.00,
    # 最后+0.01的目的是，保证输入值中没有0值，因为0是逻辑输入的极限值，逻辑函数只能无限接近0和1，而不能为0和1，此处最大值为1，是因为
    # 需要避免输出值为1即可。
    #img_data=(img_data/255.0*0.99)+0.01
    # print('最小值：',np.min(img_data))
    # print('最大值',np.max(img_data))
    # print('长度：',len(img_data))
    # for _ in img_data:
    #     print(_)
    #print(type(img_data))
    return img_data

# 通过调用上面的char_dir_names和img_to_array方法，将数据保存到文件all.csv中
def parse_to_data():
    chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
             'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
             'V', 'W', 'X', 'Y', 'Z',
             'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
             'v', 'w', 'x', 'y', 'z']
    char_dirs = []
    dirs = glob('./save_Hnd/Img/*')
    pat = r'\./save_Hnd/Img\\(Sample\d\d\d)'
    pat = re.compile(pat)
    csv_data = []
    for dir in dirs:
        r = pat.match(dir).group(1)
        char_dirs.append(r)
    char_dir_mapping = zip(chars, char_dirs)
    for t in char_dir_mapping:
        names = char_dir_names(t[1])
        for name in names:
            img_data = img_to_array2(name)
            record = np.append(t[0], img_data)
            csv_data.append(list(record))
    # 为了方便切割，对数据进行混洗
    random.shuffle(csv_data)
    print("开始写入数据......")
    # 生成数据共计3410条，数据量太少会导致过拟合情况，因此重复写入3次增加数据量
    for i in range(3):
        with open('all.csv', 'a', encoding='utf-8', newline='') as f:
            writer = csv.writer(f)
            for l in csv_data:
                writer.writerow(l)
    print("写入数据结束")

if __name__ == '__main__':
    resize_all_image()
    time.sleep(3)
    parse_to_data()



